package com.pmcc.cj.service.threads;

import com.pmcc.cj.entity.CjOrder;
import com.pmcc.cj.entity.CjOrderIndex;
import com.pmcc.cj.repository.CjOrderIndexRepository;
import com.pmcc.cj.repository.CjOrderRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用于检测该订单是否该取消
 * Created by tomas on 2020/10/19.
 */
@Transactional
@Service
public class MyThreadOrder implements Runnable  {
    private CjOrderIndexRepository cjOrderIndexRepository;
    private String id;
    private CjOrderRepository cjOrderRepository;

    public MyThreadOrder() {
    }

    public MyThreadOrder(CjOrderIndexRepository cjOrderIndexRepository, String id, CjOrderRepository cjOrderRepository) {
        this.cjOrderIndexRepository = cjOrderIndexRepository;
        this.id = id;
        this.cjOrderRepository = cjOrderRepository;
    }

    @Override
    public void run() {
        int number=0;
        while (true){
            try {
                if(number !=0){
                    CjOrderIndex orderIndex = cjOrderIndexRepository.findOne(id);
                    if(orderIndex.getPayStatus() != 1){
                        orderIndex.setPayStatus(3);
                        cjOrderIndexRepository.saveAndFlush(orderIndex);
                        //同时需要把订单表详情也改为取消状态
                        List<CjOrder> list = cjOrderRepository.findByOrderIndexId(id);
                        if(list != null && list.size()>0){
                            for(CjOrder order : list){
                                order.setPayStatus(3);
                                cjOrderRepository.saveAndFlush(order);
                            }
                        }
                    }
                    return;
                }
                number++;
                Thread.sleep(29*60*1000);//29min
            }catch (Exception e){
                return;
            }
        }
    }
}
